<?php

namespace App\Http\Controllers\Home;
use EasyWeChat\Foundation\Application;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Log;
use App\Http\Model\Goods;
use App\Http\Model\User;
use App\Http\Model\Menu;
use DB;
use Config;
use EasyWeChat\Message\Image;
use EasyWeChat\Message\Text;


class WechatController extends Controller{
    /**
     * 处理微信的请求消息
     *
     * @return string
     */
    public function serve()
    {
        Log::info('request arrived.'); # 注意：Log 为 Laravel 组件，所以它记的日志去 Laravel 日志看，而不是 EasyWeChat 日志

        $wechat = app('wechat');
        $wechat->server->setMessageHandler(function($message) use ($wechat){
            if ($message->MsgType=='event') {
                $user_openid = $message->FromUserName;
                if ($message->Event=='subscribe') {
                    $users = new User;
                    $res = $users->where('open_id',$user_openid)->first();
                    if($res){
                        if(empty($res->pid) && !empty(substr($message->EventKey, 8))){
                            $res->pid = substr($message->EventKey, 8);
                            $res->save();
                            return "嗨...来了？感谢您选中了天路本草!\n我们只做最纯正最干净的滋补养生食材！";
                        }
                        $ewmRes = is_file("upload/user/"+$user_openid+".jpg");
                        if(!$ewmRes){
                            $this->ewm_wechat($user_openid);
                        }
                        return "嗨...来了？感谢您选中了天路本草!\n我们只做最纯正最干净的滋补养生食材！";
                    }else{
                        $userService = $wechat->user;
                        $user = $userService->get($user_openid);
                        $users->open_id = $user_openid;
                        $users->username = $user['nickname'];
                        $users->face = $user['headimgurl'];
                        $users->sex = $user['sex'];
                        $users->province = $user['province'];
                        $users->city = $user['city'];
                        $users->country = $user['country'];
                        $users->pid = substr($message->EventKey, 8) or '';
                        $res = $users->save();
                        $ewmRes = is_file("upload/user/"+$user_openid+".jpg");
                        if(!$ewmRes){
                            $this->ewm_wechat($user_openid);
                        }
                        return "嗨...来了？感谢您选中了天路本草!\n我们只做最纯正最干净的滋补养生食材！";
                    }
                }else if ($message->Event=='unsubscribe') {
                    return '已取消关注';
                }else if($message->Event=='CLICK'){
                    switch ($message->EventKey) {
                        case 'ewm':
                            $res = $this->getMediaId($user_openid);
                            return $res;
                            break;
                        default:
                            break;
                    }
                }
            }else if($message->MsgType == 'text'){
                $user_openid = $message->FromUserName;
                $result = $this->serviceTemplate();
                $message = new Text(['content' => "如有任何疑问，请留言，客服会及时回复。\n客服电话0731－84455495"]);
                $wechat->staff->message($message)->to($user_openid)->send();
                return new \EasyWeChat\Message\Transfer();
            }
        });
        Log::info('return response.');
        return $wechat->server->serve();
    }
    public  function  menu_add(){
       $app = app('wechat');
       $menu = $app->menu;
       $app_id = Config::get('wechat.app_id');
       $domain_name = Config::get('app.domain_name');
       $buttons = [
            [
                "name"       => "商城",
                "sub_button" => [
                    [
                        "type" => "view",
                        "name" => "关于我们",
                        "url"  => 'http://e.eqxiu.com/s/plmDjrIs',
                    ],
                    // [
                    //     "type" => "view",
                    //     "name" => "综合商城",
                    //     "url"  => "http://sale888.cn/to/store/items?identityType=3&identityKey=569&currentStoreId=1472"
                    // ],
                    [
                        "type" => "view",
                        "name" => "旗舰店",
                        "url"  => "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$app_id."&redirect_uri=".$domain_name."&response_type=code&scope=snsapi_userinfo&state=0#wechat_redirect/"
                    ],

                ],
            ],
            [
                "name"       => "分销商",
                "sub_button" => [
                    [
                        "type" => "view",
                        "name" => "招募令",
                        "url"  => "https://s.wcd.im/v/2e5u1Z37/"
                    ],
                    [
                        "type" => "click",
                        "name" => "我的二维码",
                        "key"  => "ewm"
                    ],
                    [
                        "type" => "view",
                        "name" => "成为分销商",
                        "url"  => "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$app_id."&redirect_uri=".$domain_name."distributor&response_type=code&scope=snsapi_userinfo&state=0#wechat_redirect/"
                    ],
                ],
            ],
            [
                "name"       => "会员中心",
                "sub_button" => [
                    [
                        "type" => "view",
                        "name" => "一键拨号",
                        "url"  => "http://www.tpy10.net/yjbh.php?tel=0731-84455495"
                    ],
                    [
                        "type" => "view",
                        "name" => "一键导航",
                        "url"  => "https://map.baidu.com/mobile/webapp/place/detail/qt=inf&uid=e7d233f80e4b738514b54bf2/act=read_share&tn=B_NORMAL_MAP&hb=B_SATELLITE_STREET&t=1506409740&sharegeo=12583469.6221504%2C3251360.1702830577&vt=map"
                    ],
                    [
                        "type" => "view",
                        "name" => "个人中心",
                        "url"  => "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$app_id."&redirect_uri=".$domain_name."my&response_type=code&scope=snsapi_userinfo&state=0#wechat_redirect/"
                    ],
                    [
                        "type" => "view",
                        "name" => "积分兑换",
                        "url"  => "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$app_id."&redirect_uri=".$domain_name."integral&response_type=code&scope=snsapi_userinfo&state=0#wechat_redirect/"
                    ],

                ],
            ],

        ];
       $res = $menu->add($buttons);
       var_dump($res);
    }
    //模板消息
    public function template(){
        $app = app('wechat');
        $user = new User;
        $notice = $app->notice;
        $template_id = 'VKQRzQi8LTOt0gJRsCzzyxOH0apQ1UOfvIFcwFk5KLU';
        $url = Config::get('app.domain_name');
        $serviceInfo = $user->where('user_type')->get();
        $data = array(
            "first"=>'你好，订单支付成功',
            "keyword1"=>'天路本草',
            "keyword2"=>'微信支付',
            "keyword3"=>'300',
            "remark"=>'请及时查看物流报告',
        );
        foreach ($serviceInfo as $key => $value) {
            $res = $notice->uses($template_id)->withUrl($url)->andData($data)->andReceiver($value->open_id)->send();
        }
        return $res;
    }

    //企业提现测试
    public function business(){
        $app = $app = app('wechat');;
        $luckyMoney = $app->lucky_money;
        $orders_num = time();
        $luckyMoneyData = [
            'mch_billno'       => $orders_num,
            'send_name'        => '测试红包',
            're_openid'        => 'oHvMp0RadK2tw1WBWHiuZ5-R4iyw',
            'total_num'        => 1,  //普通红包固定为1，裂变红包不小于3
            'total_amount'     => 100,  //单位为分，普通红包不小于100，裂变红包不小于300
            'wishing'          => '祝福语',
            'client_ip'        => '123.206.80.49',  //可不传，不传则由 SDK 取当前客户端 IP
            'act_name'         => '测试活动',
            'remark'           => '测试备注',
        ];
        $result = $luckyMoney->send($luckyMoneyData, \EasyWeChat\Payment\LuckyMoney\API::TYPE_NORMAL);
        dd($result);
    }

    public function getMediaId($open_id){
        $ewmRes = is_file("upload/user/"+$open_id+".jpg");
        if(!$ewmRes){
            $this->ewm_wechat($open_id);
        }
        $file_info=array(
            'filename'=>'/upload/user/'.$open_id.'.jpg',  //相对于网站根目录的路径
            'content-type'=>'image/jpeg',  //文件类型
        );
        $imageInfo = $this->add_material($file_info);
        $text = new Image(['media_id' => $imageInfo["media_id"]]);
        return  $text;
    }
    public function add_material($file_info){
        $access_token=$this->getAccessToken();
        $url="https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={$access_token}&type=image";
        $ch = curl_init ();
        $timeout = 30;
        $real_path="{$_SERVER['DOCUMENT_ROOT']}{$file_info['filename']}";
        if(class_exists('\CURLFile')){
            $data = array("media"  => new \CURLFile($real_path));
            // dd($data);
        }else{
            $data = array("media"  => '@'.$real_path);
        }
        // $data= array("media"=>"@{$real_path}");//,'form-data'=>$file_info
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_POST, 1 );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, false );
        @curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
        $result = curl_exec ( $ch );
        curl_close ( $ch );
        if(@curl_errno($result)==0){
            return json_decode($result,true);
        }else {
            return false;
        }
    }
    //关注生成二维码
    // public function ewm_wechat($open_id){
    //     $user = new User;
    //     $userid = $user->where('open_id',$open_id)->first()->id;
    //     $tickets = UrlEncode($this->gettickt_wechat($userid));
    //     $url = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.$tickets;
    //     $img = file_get_contents($url);
    //     file_put_contents('upload/user/'.$userid.'.jpg',$img);
    //     $imgname = $open_id;
    //     $path_1 = 'http://abc.gengyong.com.cn/upload/background.jpg';
    //     $size_1 = getimagesize($path_1);
    //     $size = $size_1[0]/12*5;
    //     \Intervention\Image\Facades\Image::make($img)->resize($size, $size)->save('upload/user/'.$imgname.'.jpg');
    //     $path_2 = 'http://abc.gengyong.com.cn/upload/user/'.$imgname.'.jpg';
    //     // 创建图片对象
    //     $image_1 = imagecreatefromjpeg($path_1);
    //     $image_2 = imagecreatefromjpeg($path_2);
    //     $size_2 = getimagesize($path_2);
    //     $x = $size_1[0] - $size_2[0];
    //     $y = $size_1[1] - $size_2[1];
    //     // 合成图片
    //     imagecopymerge($image_1, $image_2, $x, $y, 0, 0, imagesx($image_2), imagesy($image_2), 100);
    //     // 输出合成图片
    //     Imagejpeg($image_1, 'upload/user/'.$imgname.'.jpg');
    // }
    public function ewm(){
        $this->ewm_wechat('oPZoxwP-rQEe36m7ipS6RE80SanU');
    }
    public function ewm_wechat($open_id){
        $user = new User;
        $userInfo = $user->where('open_id',$open_id)->first();
        $userid = $userInfo->id;
        $tickets = UrlEncode($this->gettickt_wechat($userid));
        $url = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.$tickets;
        $img = file_get_contents($url);
        $imgname = $open_id;
        $face = $userInfo->face;
        $username = $userInfo->username;

        $path_1 = Config::get('app.domain_name').'upload/background.jpg';
        $size_1 = getimagesize($path_1);
        $size = $size_1[0]*116/475;
        file_put_contents('upload/user/'.$userid.'.jpg',$img);
        \Intervention\Image\Facades\Image::make($img)->resize($size, $size)->save('upload/user/'.$imgname.'.jpg');
        $path_2 = Config::get('app.domain_name').'upload/user/'.$imgname.'.jpg';
        // 创建图片对象
        $image_1 = imagecreatefromjpeg($path_1);
        $image_2 = imagecreatefromjpeg($path_2);
        $size_2 = getimagesize($path_2);
        $x = $size_1[0]*179/475;
        $y = $size_1[1]*720/1381;
        // 合成图片
        imagecopymerge($image_1, $image_2, $x, $y, 0, 0, imagesx($image_2), imagesy($image_2), 100);


        Imagejpeg($image_1, 'upload/user/'.$imgname.'.jpg');


        $dst_path = 'upload/user/'.$imgname.'.jpg';
        //创建图片的实例
        $dst = imagecreatefromstring(file_get_contents($dst_path));
        //打上文字
        $font = 'simsun/simsun.ttc';//字体路径

        $black = imagecolorallocate($dst, 255,204,0);//字体颜色
        imagefttext($dst, 26, 0, 400, 275, $black, $font, $username);
        imagefttext($dst, 26, 0, 401, 275, $black, $font, $username);
        imagefttext($dst, 26, 0, 402, 275, $black, $font, $username);
        imagefttext($dst, 26, 0, 403, 275, $black, $font, $username);
        
        //输出图片
        list($dst_w, $dst_h, $dst_type) = getimagesize($dst_path);
        Imagejpeg($dst, 'upload/user/'.$imgname.'.jpg');



        // $path_4 = Config::get('app.domain_name').'upload/user/'.$imgname.'.jpg';
        // $image_4 = imagecreatefromjpeg($path_4);
        // // if(!file_exists('upload/user-face/'.$imgname.'.png')){
        // //     $face_url = file_get_contents($face);
        // //     file_put_contents('upload/user-face/'.$imgname.'.png', $face_url);
        // // }
        // // $path_3 = Config::get('app.domain_name').'upload/user-face/'.$imgname.'.png';
        // $path_3 = $face.'.png';
        // $image_3 = imagecreatefrompng($path_3);
        // $size_3 = getimagesize($path_3);
        // $size_4 = getimagesize($path_4);
        // $x2 = $size_4[0]*113/275;
        // $y2 = $size_4[1]/160;
        // imagecopymerge($image_4, $image_3, $x2, $y2, 0, 0, imagesx($image_3), imagesy($image_3), 100);
        // // 输出合成图片
        // Imagejpeg($image_4, 'upload/user/'.$imgname.'.jpg');
        return true;
    }
    public function gettickt_wechat($userid){
        $accessToken = $this->getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$accessToken;
        $uid = $userid;
        $post = "{\"action_name\": \"QR_LIMIT_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": $uid}}";

        $res = $this->httpRequest($url, $post);
        $data = json_decode($res,true);
        return $data['ticket'];
    }
}
